<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\system;

use app\admin\model\publicuse\MyCurd;
use app\admin\model\publicuse\PublicUse;
use app\admin\model\SystemMenu;
use app\admin\model\SystemNode;
use app\admin\service\TriggerService;
use app\common\constants\MenuConstant;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use app\common\controller\AdminController;
use think\App;
use think\facade\Db;
use think\Request;

/**
 * Class Menu
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="菜单管理",auth=true)
 */
class Menu extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'sort' => 'desc',
        'id'   => 'asc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemMenu();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            $count = $this->model->count();
            $list = $this->model->order($this->sort)->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add($id = null)
    {
//        echo $id;exit;
        $homeId = $this->model
            ->where([
                'pid' => MenuConstant::HOME_PID,
            ])
            ->value('id');
        if ($id == $homeId) {
            $this->error('首页不能添加子菜单');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'pid|上级菜单'   => 'require',
                'title|菜单名称' => 'require',
                'icon|菜单图标'  => 'require',
            ];
            $this->validate($post, $rule);
            if(isset($post['curd'])){
                $post['curd'] = 1;
            }else{
                $post['curd'] = 0;
            }
//            return json($post);
            if(isset($post['default_tablebar'])&&$post['default_tablebar']){
                $post['default_tablebar'] = json_encode($post['default_tablebar'],JSON_UNESCAPED_UNICODE);
            }
            if(isset($post['default_right_button'])&&$post['default_right_button']){
                $post['default_right_button'] = json_encode($post['default_right_button'],JSON_UNESCAPED_UNICODE);
            }
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                TriggerService::updateMenu();
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $pidMenuList = $this->model->getPidMenuList();
        $row = [];
        if(!empty($id)){
            $row = $this->model->where('id',$id)
                ->findOrEmpty()->toArray();
        }
        $newdata = PublicUse::getApp();
        $this->assign('app',$newdata);
        $this->assign('id', $id);
        $this->assign('row', $row);
        $this->assign('pidMenuList', $pidMenuList);
        $this->assign('getTableList', $this->model->getTableList());
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'pid|上级菜单'   => 'require',
                'title|菜单名称' => 'require',
                'icon|菜单图标'  => 'require',
            ];
            $this->validate($post, $rule);
            if(isset($post['curd'])){
                $post['curd'] = 1;
            }else{
                $post['curd'] = 0;
            }
            if(isset($post['default_tablebar'])&&$post['default_tablebar']){
                $post['default_tablebar'] = json_encode($post['default_tablebar'],JSON_UNESCAPED_UNICODE);
            }else{
                $post['default_tablebar'] = '';
            }
            if(isset($post['default_right_button'])&&$post['default_right_button']){
                $post['default_right_button'] = json_encode($post['default_right_button'],JSON_UNESCAPED_UNICODE);
            }else{
                $post['default_right_button'] = '';
            }
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                TriggerService::updateMenu();
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $pidMenuList = $this->model->getPidMenuList();
        if($row->default_tablebar){
            $row->default_tablebar = json_decode($row->default_tablebar,true);
        }else{
            $row->default_tablebar = [];
        }
        if($row->default_right_button){
            $row->default_right_button = json_decode($row->default_right_button,true);
        }else{
            $row->default_right_button = [];
        }
        $this->assign([
            'id'          => $id,
            'pidMenuList' => $pidMenuList,
            'row'         => $row,
        ]);
//        echo '<pre>';
//        print_r($row);
//        exit;
        $this->assign('getTableList', $this->model->getTableList());
        $newdata = PublicUse::getApp();
        $this->assign('app',$newdata);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        empty($row) && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        if ($save) {
            TriggerService::updateMenu();
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        $homeId = $this->model
            ->where([
                'pid' => MenuConstant::HOME_PID,
            ])
            ->value('id');
        if ($post['id'] == $homeId && $post['field'] == 'status') {
            $this->error('首页状态不允许关闭');
        }
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        TriggerService::updateMenu();
        $this->success('保存成功');
    }

    /**
     * @NodeAnotation(title="添加菜单提示")
     */
    public function getMenuTips()
    {
        $node = input('get.keywords');
        $list = SystemNode::whereLike('node', "%{$node}%")
            ->field('node,title')
            ->limit(10)
            ->select();
        return json([
            'code'    => 0,
            'content' => $list,
            'type'    => 'success',
        ]);
    }
    /**
     * @NodeAnotation(title="一键crud")
     */
    public function crud(Request $request){
        $id = $request->param('id','');
        $shuju = $this->model->find($id);
        if($shuju->curd!=1){
            return $this->error('本菜单不能curd');
        }
        if(empty($shuju->table)){
            return $this->error('菜单没有添加模型');
        }
        if(empty($shuju->href)){
            return $this->error('菜单没有链接');
        }
        if($request->isAjax()){
            $modelfield = PublicUse::getModelAndField($shuju->table);
            $curds = $request->param('curds',[]);
            if(in_array('files',$curds)){
//                dump($curds);die();
                $file_names = explode('/',$shuju->href);
                $file_names = explode('.',$file_names[0]);
//        echo $str;exit;
                if(count($file_names)==2){
                    $file_dir = root_path().'app'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'controller'.DIRECTORY_SEPARATOR.$file_names[0].DIRECTORY_SEPARATOR.'field';
                }else{
                    $file_dir = root_path().'app'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'controller'.DIRECTORY_SEPARATOR.'field';
                }
//        echo $file_dir;exit;
                if(!is_dir($file_dir)){
                    chmod(root_path().'app'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'controller',0777);
                    mkdir($file_dir,0777,true);
                }
                if(isset($file_names[1])){
                    $bool = file_put_contents($file_dir.DIRECTORY_SEPARATOR.ucfirst($file_names[1]).'.txt',json_encode($modelfield,JSON_UNESCAPED_UNICODE));
                }else{
                    $bool = file_put_contents($file_dir.DIRECTORY_SEPARATOR.ucfirst($file_names[0]).'.txt',json_encode($modelfield,JSON_UNESCAPED_UNICODE));
                }
                if(!$bool){
                    return $this->error('生成字段文件失败');
                }
            }
//            $model_array = PublicUse::getModeToArray($shuju->table);

            $obj = new MyCurd();
            if(in_array('model',$curds)){
                $bool = $obj->create_model($modelfield);
                if(!$bool){
                    return $this->error('生成模型失败');
                }
            }
            if(in_array('class',$curds)){
                $bool = $obj->create_class($modelfield,$shuju->title,$shuju->toArray()['href']);
                if(!$bool){
                    return $this->error('生成控制器失败');
                }
            }
//            dump($curds);die();
            if(in_array('html',$curds)){
                $bool = $obj->create_html($modelfield,$shuju->toArray());
                if(!$bool){
                    return $this->error('生成html失败');
                }
            }
//        echo '<pre>';
//        print_r($modelfield);
//        exit;
//            dump($curds);die();
            return $this->success('crud成功');
        }
        $this->assign('id',$id);
        return $this->fetch();

    }
    /**
     * @NodeAnotation(title="更新字段文件")
     */
    public function updateField($id){
        $shuju = $this->model->find($id);
//        if($shuju->curd!=1){
//            return $this->error('本菜单不能curd');
//        }
        if(empty($shuju->table)){
            return $this->error('菜单没有添加模型');
        }
        if(empty($shuju->href)){
            return $this->error('菜单没有链接');
        }
        $modelfield = PublicUse::getModelAndField($shuju->table);
        $model_array = PublicUse::getModeToArray($shuju->table);


        $file_names = explode('/',$shuju->href);
        $file_names = explode('.',$file_names[0]);
//        echo $str;exit;
        if(count($file_names)==2){
            $file_dir = root_path().'app'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'controller'.DIRECTORY_SEPARATOR.$file_names[0].DIRECTORY_SEPARATOR.'field';
        }else{
            $file_dir = root_path().'app'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'controller'.DIRECTORY_SEPARATOR.'field';
        }
//        echo $file_dir;exit;
        if(!is_dir($file_dir)){
            chmod(root_path().'app'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'controller',0777);
            mkdir($file_dir,0777,true);
        }
        if(isset($file_names[1])){
            $bool = file_put_contents($file_dir.DIRECTORY_SEPARATOR.ucfirst($file_names[1]).'.txt',json_encode($modelfield,JSON_UNESCAPED_UNICODE));
        }else{
            $bool = file_put_contents($file_dir.DIRECTORY_SEPARATOR.ucfirst($file_names[0]).'.txt',json_encode($modelfield,JSON_UNESCAPED_UNICODE));
        }
        if(!$bool){
            return $this->error('生成字段文件失败');
        }
        return $this->success('更新字段文件成功');
    }
}